/*
 * Scheduler.cpp
 *
 *  Created on: 24.09.2012
 *      Author: Lapchinskiy
 */
//#include "Global_includes.h"
//#include "Logging.h"
//#include "Global_includes.h"
#include "BuildConfig.h"
#include "Global_types.h"
#include "Block.h"
#include "ArrayList.h"
#include "Condition.h"
#include "ConditionBlock.h"
#include "Task.h"
#include "TimeManager.h"
#include "CommandHandler.h"
#include "Scheduler.h"
volatile uint32_t Scheduler::eventMask;
volatile uint32_t Scheduler::cachedEventMask;
ArrayList* Scheduler::threadList = NULL;
bool Scheduler::schedEnable = FALSE;
volatile uint32_t null=0;
Scheduler::Scheduler()
  {

  }
ErrorCode Scheduler::init(void)
  {
//	for(uint8_t i=0; i<MAX_EVENT_NUMBER;i++)
    Scheduler::threadList = new ArrayList;
#ifdef TERMINAL_CONTROL_ENABLE
//    volatile uint32_t *timeptr;
//     timeptr = TimeManager::GetSystemTime();
   Block* condCommHandleBlock=CommandHandler::Init(&cachedEventMask);
   addThreadEntry(condCommHandleBlock);
#endif //ERMINAL_CONTROL_ENABLE
    return NO_ERR;
  }

ErrorCode Scheduler::start(void)
  {
    schedEnable = TRUE;
     TimeManager::enabled = TRUE;
    while (schedEnable)
      {
//        while (!eventMask)
//          { //Waiting for event to occur
//            kickTheDog(); //reseting the watchdog
//          }
//        for (uint8_t i = 0; i < MAX_EVENT_NUMBER; i++)
//          {
//            if ((eventMask & (uint8_t(1 << i)))||(i==ALL))
//              { //select event from mask
//                eventMask &= (~uint8_t(1 << i)); //clear event from mask

 //       TimeManager::enabled = FALSE;
        cachedEventMask=eventMask;
        eventMask=0; //clear events
        for (uint8_t j = 0; j < threadList->getLength(); j++)
          { //all event listener running cycle
            Block *nextblockInChain;
         //   TimeManager::enabled=FALSE;
            nextblockInChain = ((Block*) threadList->get(j))->step(); //run event listener and get next task from chain;
           // TimeManager::enabled = TRUE;
            threadList->add((void*) nextblockInChain, j);
          }
     //   TimeManager::enabled = TRUE;
//              }
//          }
      }
    return NO_ERR;
  }
//ErrorCode Scheduler::sendEvent(uint8_t event) {
//	Scheduler::eventMask |= uint32_t(1 << event);
//	return NO_ERR;
//}

ErrorCode Scheduler::waitForEvent(void)
  {
    while (!eventMask)
      {

      }
    return NO_ERR;
  }

ErrorCode Scheduler::addThreadEntry(Block *blockToAdd)
  {
    threadList->add((void*) blockToAdd);
    return NO_ERR;
  }

ErrorCode Scheduler::stop(void)
  {
    schedEnable = FALSE;
    return NO_ERR;
  }

ArrayList* Scheduler::getThreadList(void)
  {
    return threadList;
  }

ErrorCode Scheduler::kickTheDog(void)
  {
    return NO_ERR;
  }

Scheduler::~Scheduler()
  {
    delete threadList;
  }

